package com.example.idachuappone.order.item;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo.ShareParams;
import cn.sharesdk.wechat.moments.WechatMoments;

import com.example.idachuappone.BaseActivity;
import com.example.idachuappone.LoadingActivity;
import com.example.idachuappone.MainTWo;
import com.example.idachuappone.R;
import com.example.idachuappone.cook.entity.CookResult;
import com.example.idachuappone.index.dto.WelcomeDto;
import com.example.idachuappone.index.ui.MyGridView;
import com.example.idachuappone.order.adapter.AdapterUploading;
import com.example.idachuappone.order.entity.ImageBucket;
import com.example.idachuappone.order.imageutil.AlbumHelper;
import com.example.idachuappone.order.imageutil.Bimp;
import com.example.idachuappone.utils.AppShareData;
import com.example.idachuappone.utils.CheckUtil;
import com.example.idachuappone.utils.Constant;
import com.example.idachuappone.utils.CusProSmallBgDialog;
import com.example.idachuappone.utils.FileUtil;
import com.example.idachuappone.utils.MainToast;
import com.example.idachuappone.utils.NetUtil;
import com.example.idachuappone.utils.PrefUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig.BitmapCacheManagementTask;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class SubmitCommentActivity extends BaseActivity implements OnRatingBarChangeListener, OnClickListener,
		OnItemClickListener {
	public static Bitmap bimap;
	private AdapterUploading adapterUploading;
	private Button btn_back;
	private Button btn_submit;
	private CookResult cookResult;
	private CusProSmallBgDialog cusProSmallBgDialog;
	private EditText et_content;
	private MyGridView gridView;
	private Handler handler;
	private AlbumHelper helper;
	private HttpUtils httpUtils;
	int i;
	private String id;
	private int imageDeleteRequest;
	private int imageRequest;
	private ImageView img_isName;
	private ImageView img_isfriend;
	private String[] imgs;
	private boolean isName;
	private boolean isfriend;
	private List<String> list;
	List<ImageBucket> listBuckets;
	private PlatformActionListener paListener;
	private String paramScore;
	private RatingBar rbar_comment_star;
	private TextView tv_comment_content;
	private TextView tv_comment_title;
	private TextView tv_friend_content;

	public SubmitCommentActivity() {
		this.paramScore = "0.0";
		this.imageRequest = 255;
		this.imageDeleteRequest = 4095;
		this.imgs = new String[10];
		this.isName = false;
		this.isfriend = false;
		this.handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 111 /* 111 */:
					MainToast.show(SubmitCommentActivity.this, "\u5206\u4eab\u5931\u8d25", 0);
				case 1111:
					MainToast.show(SubmitCommentActivity.this, "\u5206\u4eab\u6210\u529f", 1);
					SubmitCommentActivity.this.shareOk();
				case 11111:
					MainToast.show(SubmitCommentActivity.this, "\u5206\u4eab\u53d6\u6d88", 0);
				default:
				}
			}
		};
		this.paListener = new PlatformActionListener() {
			@Override
			public void onError(Platform platform, int action, Throwable t) {
				SubmitCommentActivity.this.handler.sendEmptyMessage(111);
			}

			@Override
			public void onComplete(Platform arg0, int arg1, HashMap<String, Object> hashMap) {
				SubmitCommentActivity.this.handler.sendEmptyMessage(1111);
			}

			@Override
			public void onCancel(Platform platform, int action) {
				SubmitCommentActivity.this.handler.sendEmptyMessage(11111);
			}
		};
	}

	private void shareOk() {
		Map<String, String> map = new HashMap();
		map.put("id", this.id);
		NetUtil.post(this, Constant.SHARE_OK_ADD, map, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
			}
		});
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_submit_comment);
		ShareSDK.initSDK(this);
		Bimp.drr = new ArrayList();
		this.cusProSmallBgDialog = new CusProSmallBgDialog(this);
		this.cusProSmallBgDialog.setCancelable(false);
		this.cookResult = (CookResult) getIntent().getExtras().getSerializable("cookResult");
		this.id = getIntent().getExtras().getString("id");
		this.httpUtils = new HttpUtils();
		initView();
		initData();
	}

	private void initView() {
		this.tv_friend_content = (TextView) findViewById(R.id.tv_friend_content);
		this.tv_comment_content = (TextView) findViewById(R.id.tv_comment_content);
		this.tv_comment_title = (TextView) findViewById(R.id.tv_comment_title);
		this.btn_back = (Button) findViewById(R.id.btn_back);
		this.btn_back.setOnClickListener(this);
		this.et_content = (EditText) findViewById(R.id.et_content);
		this.btn_submit = (Button) findViewById(R.id.btn_submit);
		this.btn_submit.setOnClickListener(this);
		this.img_isName = (ImageView) findViewById(R.id.img_isName);
		this.img_isName.setOnClickListener(this);
		this.img_isfriend = (ImageView) findViewById(R.id.img_isfriend);
		this.img_isfriend.setOnClickListener(this);
		this.rbar_comment_star = (RatingBar) findViewById(R.id.rbar_comment_star);
		this.rbar_comment_star.setOnRatingBarChangeListener(this);
		this.rbar_comment_star.setRating(Float.valueOf(this.paramScore).floatValue());
		this.gridView = (MyGridView) findViewById(R.id.gridView1);
		this.gridView.setOnItemClickListener(this);
		this.adapterUploading = new AdapterUploading(this);
		this.gridView.setAdapter(this.adapterUploading);
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View arg1, int position, long arg3) {
		Intent intent;
		if (this.list.get(position) == null || this.list.get(position).length() <= 0) {
			this.helper = new AlbumHelper();
			this.helper.init(getApplicationContext());
			this.listBuckets = this.helper.getImagesBucketList(false);
			intent = new Intent(this, ImageGridActivity.class);
			intent.putExtra("listBuckets", (Serializable) this.listBuckets);
			int index = 0;
			for (int i = 0; i < this.listBuckets.size(); i++) {
				if (this.listBuckets.get(i).bucketName.equals("Camera")) {
					index = i;
					break;
				}
			}
			intent.putExtra("index", index);
			if (this.listBuckets == null || this.listBuckets.size() <= 0) {
				MainToast.show(this, "\u624b\u673a\u6682\u65e0\u7167\u7247", 0);
				return;
			} else {
				startActivityForResult(intent, this.imageRequest);
				return;
			}
		}
		intent = new Intent(this, MyOrderImageDeleteActivity.class);
		intent.putExtra("index", position);
		startActivityForResult(intent, this.imageDeleteRequest);
	}

	private void initData() {
		if (LoadingActivity.welcome.getAwards().getFriend() != null) {
			String comment = LoadingActivity.welcome.getAwards().getComment().getText();
			if (comment.indexOf("|") != -1) {
				this.tv_comment_content.setText(comment.substring(0, comment.indexOf("|")));
				this.tv_comment_title.setText(comment.substring(comment.indexOf("|") + 1));
			} else {
				this.tv_comment_content.setText(comment);
				this.tv_comment_title.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
			}
			this.tv_friend_content.setText(LoadingActivity.welcome.getAwards().getFriend().getText());
		} else {
			initContent();
		}
		this.helper = new AlbumHelper();
		this.helper.init(getApplicationContext());
		this.listBuckets = this.helper.getImagesBucketList(false);
		bimap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_carmera);
		this.list = new ArrayList();
		this.list.add(null);
		initAdapter();
	}

	private void initContent() {
		NetUtil.get(this, Constant.PACKAGES, 100, new RequestCallBack<String>() {
			@Override
			public void onFailure(HttpException arg0, String arg1) {
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String json = NetUtil.unescapeUnicode(responseInfo.result);
				try {
					LoadingActivity.welcome = new WelcomeDto().getWelcome(SubmitCommentActivity.this, json);
					String comment = LoadingActivity.welcome.getAwards().getComment().getText();
					if (comment.indexOf("|") != -1) {
						SubmitCommentActivity.this.tv_comment_content.setText(comment.substring(0, comment.indexOf("|")));
						SubmitCommentActivity.this.tv_comment_title.setText(comment.substring(comment.indexOf("|") + 1));
					} else {
						SubmitCommentActivity.this.tv_comment_content.setText(comment);
						SubmitCommentActivity.this.tv_comment_title
								.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
					}
					SubmitCommentActivity.this.tv_friend_content.setText(LoadingActivity.welcome.getAwards()
							.getFriend().getText());
				} catch (Exception e) {
					MainToast.show(SubmitCommentActivity.this, e.getMessage(), 0);
				}
			}
		});
	}

	private void initAdapter() {
		this.adapterUploading.setList(this.list);
		this.adapterUploading.notifyDataSetChanged();
	}

	@Override
	public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
		if (rating >= 0.0f && (rating) <= 1.0d) {
			rating = 1.0f;
			ratingBar.setRating(1.0f);
		} else if ((rating) > 1.0d && (rating) <= 2.0d) {
			rating = 2.0f;
			ratingBar.setRating(2.0f);
		} else if ((rating) > 2.0d && (rating) <= 3.0d) {
			rating = 3.0f;
			ratingBar.setRating(3.0f);
		} else if ((rating) <= 3.0d || (rating) > 4.0d) {
			rating = 5.0f;
			ratingBar.setRating(5.0f);
		} else {
			rating = 4.0f;
			ratingBar.setRating(4.0f);
		}
		this.paramScore = String.valueOf(rating);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back /* 2131165198 */:
			if (Float.valueOf(this.paramScore).floatValue() > 0.0f) {
				dialogBack();
			} else if (this.et_content.getText().toString().trim().length() > 0) {
				dialogBack();
			} else if (this.list == null || this.list.size() <= 1) {
				finish();
			} else {
				dialogBack();
			}
		case R.id.btn_submit /* 2131165282 */:
			if (!CheckUtil.checkNet(this)) {
				MainToast.show(this, getResources().getString(R.string.txt_network), 0);
			} else if (Float.valueOf(this.paramScore).floatValue() <= 0.0f) {
				MainToast.show(this, "\u8bf7\u60a8\u7ed9\u5927\u53a8\u8bc4\u4e0b\u661f\u7ea7\u5427", 0);
			} else if (this.et_content.getText().toString().trim().length() == 0) {
				MainToast.show(this, "\u8bf7\u60a8\u586b\u5199\u5efa\u8bae", 0);
			} else {
				this.cusProSmallBgDialog.setMsg("\u63d0\u4ea4\u8bc4\u8bba\u4e2d");
				this.cusProSmallBgDialog.show();
				if (this.list == null || this.list.size() <= 0) {
					submitComment();
				} else if (this.list.get(0) == null || this.list.get(0).length() <= 0) {
					submitComment();
				} else {
					shangChuan(this.list.get(0));
				}
			}
		case R.id.img_isName /* 2131165418 */:
			if (this.isName) {
				this.img_isName.setImageResource(R.drawable.icon_select);
				this.isName = false;
				return;
			}
			this.img_isName.setImageResource(R.drawable.icon_select_p);
			this.isName = true;
		case R.id.img_isfriend /* 2131165420 */:
			if (this.isfriend) {
				this.img_isfriend.setImageResource(R.drawable.icon_select);
				this.isfriend = false;
				return;
			}
			this.img_isfriend.setImageResource(R.drawable.icon_select_p);
			this.isfriend = true;
		default:
		}
	}

	public void dialogBack() {
		new Builder(this).setMessage("\u662f\u5426\u653e\u5f03\u8bc4\u4ef7")
				.setPositiveButton("\u653e\u5f03", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						SubmitCommentActivity.this.finish();
					}
				}).setNegativeButton("\u53d6\u6d88", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == 4) {
			if (Float.valueOf(this.paramScore).floatValue() > 0.0f) {
				dialogBack();
				return true;
			} else if (this.et_content.getText().toString().trim().length() > 0) {
				dialogBack();
				return true;
			} else if (this.list != null && this.list.size() > 1) {
				dialogBack();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void weiXin() {
		ShareParams spweixinf = new ShareParams();
		spweixinf
				.setTitle("\u521a\u4f53\u9a8c\u4e86\u7231\u5927\u53a8"
						+ this.cookResult.getName()
						+ "\u53a8\u5e08\u7684\u670d\u52a1\uff0c\u63a8\u8350\u7ed9\u4f60\uff0c\u5feb\u53bb\u9884\u7ea6\u5427\uff01");
		spweixinf
				.setText("69\u5143\u7ea6\u4e2a\u79c1\u53a8\u4e0a\u95e8\u505a\u996d\uff0c\u7a9d\u5728\u6c99\u53d1\u4e0a\u770b\u5b8c\u7535\u89c6\uff0c\u7f8e\u5473\u4f73\u80b4\u5c31\u4e0a\u684c\u5566\uff01");
		spweixinf.setImageUrl(this.cookResult.getHead());
		spweixinf.setUrl(new StringBuilder(Constant.COOK_SHARE_CONTENT).append(this.cookResult.getId()).toString());
		spweixinf.setShareType(BitmapCacheManagementTask.MESSAGE_CLEAR);
		Platform weixinf = ShareSDK.getPlatform(WechatMoments.NAME);
		weixinf.setPlatformActionListener(this.paListener);
		weixinf.share(spweixinf);
	}

	private void submitComment() {
		RequestParams params = new RequestParams();
		HttpUtils httpUtils = new HttpUtils();
		params.setHeaders(NetUtil.getHeaders(this));
		params.addBodyParameter("id", this.id);
		params.addBodyParameter("star", this.paramScore);
		if (this.isName) {
			params.addBodyParameter("anonymous", "1");
		} else {
			params.addBodyParameter("anonymous", "0");
		}
		params.addBodyParameter("content", this.et_content.getText().toString());
		int i = 0;
		while (i < this.imgs.length && this.imgs[i] != null && this.imgs[i].length() > 0) {
			params.addBodyParameter("img[]", this.imgs[i]);
			i++;
		}
		httpUtils.send(HttpMethod.POST, Constant.SUBMITCOMMENT, params, new RequestCallBack<String>() {
			@Override
			public void onFailure(HttpException arg0, String arg1) {
				SubmitCommentActivity.this.cusProSmallBgDialog.dismiss();
				MainToast.show(SubmitCommentActivity.this,
						SubmitCommentActivity.this.getResources().getString(R.string.netFail), 0);
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				SubmitCommentActivity.this.cusProSmallBgDialog.dismiss();
				try {
					JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(responseInfo.result));
					if (jsonObject.getInt("code") == 10000) {
						AppShareData.isRefreshOrderAll = true;
						AppShareData.isRefreshOrderPay = true;
						AppShareData.isRefreshOrderComment = true;
						SubmitCommentActivity.this.startActivity(new Intent(SubmitCommentActivity.this, MainTWo.class));
						if (SubmitCommentActivity.this.isfriend) {
							SubmitCommentActivity.this.weiXin();
							return;
						}
						return;
					}
					MainToast.show(SubmitCommentActivity.this, jsonObject.getString("error"), 0);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (AppShareData.isRefreshImageUpload) {
			updateImageList();
			AppShareData.isRefreshImageUpload = false;
		}
	}

	private void updateImageList() {
		if (Bimp.drr.size() < 10) {
			this.list = new ArrayList();
			this.list.addAll(Bimp.drr);
			this.list.add(null);
		} else {
			this.list = new ArrayList();
			this.list.addAll(Bimp.drr);
		}
		this.adapterUploading.setList(this.list);
		this.adapterUploading.notifyDataSetInvalidated();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == this.imageRequest && resultCode == -1) {
			updateImageList();
		}
		if (requestCode == this.imageDeleteRequest && resultCode == -1 && data.getBooleanExtra("isupdate", false)) {
			if (Bimp.drr.size() < 10) {
				this.list = new ArrayList();
				this.list.addAll(Bimp.drr);
				this.list.add(null);
			} else {
				this.list = new ArrayList();
				this.list.addAll(Bimp.drr);
			}
			this.adapterUploading.setList(this.list);
			this.adapterUploading.notifyDataSetInvalidated();
		}
	}

	private void shangChuan(String path) {
		if (CheckUtil.checkNet(this)) {
			RequestParams params = new RequestParams();
			File file = new File(path);
			Options options = new Options();
			try {
				BitmapFactory.decodeFile(path, options);
				options.inJustDecodeBounds = true;
				options.inSampleSize = computeSampleSize(options, -1, 1400);
				Log.e("computeSampleSize(options,-1,1400)",
						new StringBuilder(String.valueOf(computeSampleSize(options, -1, 1400))).toString());
				options.inJustDecodeBounds = false;
			} catch (Exception e) {
				options.inSampleSize = 4;
			}
			Bitmap bitmap = BitmapFactory.decodeFile(path, options);
			try {
				file = saveMyBitmap(getPicStoreName("head"), bitmap);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			if (bitmap.isRecycled()) {
				bitmap.recycle();
			}
			params.addBodyParameter("file", file);
			params.setHeader("Cookie",
					"auth=" + URLEncoder.encode(String.valueOf(PrefUtil.getInstance(this).getAuth())));
			this.httpUtils.send(HttpMethod.POST, Constant.UPLOAD, params, new RequestCallBack<String>() {
				@Override
				public void onStart() {
					super.onStart();
				}

				@Override
				public void onLoading(long total, long current, boolean isUploading) {
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(responseInfo.result));
						if (jsonObject.getInt("code") == 10000) {
							SubmitCommentActivity.this.imgs[SubmitCommentActivity.this.i] = jsonObject.getJSONObject(
									"data").getString("value");
							SubmitCommentActivity submitCommentActivity = SubmitCommentActivity.this;
							submitCommentActivity.i++;
							if (SubmitCommentActivity.this.i >= SubmitCommentActivity.this.list.size()) {
								SubmitCommentActivity.this.submitComment();
								return;
							} else if (SubmitCommentActivity.this.list.get(SubmitCommentActivity.this.i) == null
									|| SubmitCommentActivity.this.list.get(SubmitCommentActivity.this.i).toString()
											.length() <= 0) {
								SubmitCommentActivity.this.submitComment();
								return;
							} else {
								SubmitCommentActivity.this.shangChuan(SubmitCommentActivity.this.list
										.get(SubmitCommentActivity.this.i));
								return;
							}
						}
						SubmitCommentActivity.this.cusProSmallBgDialog.dismiss();
						MainToast.show(SubmitCommentActivity.this, jsonObject.getString("error"), 0);
					} catch (JSONException e) {
						SubmitCommentActivity.this.cusProSmallBgDialog.dismiss();
						e.printStackTrace();
					}
				}

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					SubmitCommentActivity.this.cusProSmallBgDialog.dismiss();
					MainToast.show(SubmitCommentActivity.this,
							SubmitCommentActivity.this.getResources().getString(R.string.netFail), 0);
				}
			});
			return;
		}
		MainToast.show(this, getResources().getString(R.string.txt_network), 0);
	}

	public File saveMyBitmap(String bitName, Bitmap mBitmap) throws IOException {
		File f = new File(FileUtil.getUserHeadIcDir(), bitName);
		f.createNewFile();
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		mBitmap.compress(CompressFormat.JPEG, 100, fOut);
		try {
			fOut.flush();
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e22) {
			e22.printStackTrace();
		}
		return f;
	}

	private String getPicStoreName(String type) {
		return new StringBuilder(String.valueOf(type))
				.append(new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date(System.currentTimeMillis())))
				.append(".jpg").toString();
	}

	public int computeSampleSize(Options options, int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
		Log.e("aaaaa", new StringBuilder(String.valueOf(initialSize)).toString());
		if (initialSize > 8) {
			return ((initialSize + 7) / 8) * 8;
		}
		int roundedSize = 1;
		while (roundedSize < initialSize) {
			roundedSize <<= 1;
		}
		return roundedSize;
	}

	private int computeInitialSampleSize(Options options, int minSideLength, int maxNumOfPixels) {
		int w = options.outWidth;
		int h = options.outHeight;
		if (w <= maxNumOfPixels && h <= maxNumOfPixels) {
			return 1;
		}
		int scaleX = w / maxNumOfPixels;
		int scaleY = h / maxNumOfPixels;
		return scaleX > scaleY ? scaleX + 1 : scaleY + 1;
	}
}